<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="jobType">
        <el-select
          v-model="queryParams.jobType"
          placeholder="请选择任务类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.check_tasktype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.taskstatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['console:taskCheck:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['console:taskCheck:remove']"
          >删除</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="taskCheckList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="55">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"></span>
        </template>
      </el-table-column>
      <el-table-column label="任务编号" prop="id" align="center" />
      <el-table-column
        label="任务名称"
        align="center"
        prop="taskName"
        width="75"
      />
      <el-table-column label="任务模式" align="center" prop="taskType" />
      <el-table-column label="任务类型" align="center" prop="jobType">
        <template slot-scope="scope">
          <div v-for="dict in dict.type.all_tasktype" :key="dict.value">
            {{ dict.value == scope.row.jobType ? dict.label : "" }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="源实例名" align="center" prop="sourceName" />
      <el-table-column label="目标实例名" align="center" prop="sinkName" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="更新时间"
        width="140"
        align="center"
        prop="updateTime"
      />
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <span v-for="dict in dict.type.taskstatus" :key="dict.value">
            <el-tag
              v-if="scope.row.taskStatus == dict.value"
              :type="dict.raw.listClass"
            >
              {{ dict.label }}
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="120"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleExecute(scope.row)"
            v-if="scope.row.taskStatus != 0"
            v-hasPermi="['console:taskCheck:execute']"
            style="color: #42d885"
            >执行</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleResult(scope.row)"
            v-hasPermi="['console:taskCheck:result']"
            >记录</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleNewResult(scope.row)"
            v-hasPermi="['console:tasks:resultLog']"
            >结果</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleResultLog(scope.row)"
            v-hasPermi="['console:tasks:resultLog']"
            >日志</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['console:taskCheck:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['console:taskCheck:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pgNum"
      :limit.sync="queryParams.pgSize"
      @pagination="getList"
    />

    <!-- 添加或修改校验任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务模式" prop="taskMode">
          <el-input v-model="form.taskMode" placeholder="请输入任务模式" />
        </el-form-item>
        <el-form-item label="源数据库id" prop="sourceId">
          <el-input v-model="form.sourceId" placeholder="请输入源数据库id" />
        </el-form-item>
        <el-form-item label="源数据库name" prop="sourceName">
          <el-input
            v-model="form.sourceName"
            placeholder="请输入源数据库name"
          />
        </el-form-item>
        <el-form-item label="目标数据库id" prop="sinkId">
          <el-input v-model="form.sinkId" placeholder="请输入目标数据库id" />
        </el-form-item>
        <el-form-item label="目标数据库name" prop="sinkName">
          <el-input
            v-model="form.sinkName"
            placeholder="请输入目标数据库name"
          />
        </el-form-item>
        <el-form-item label="任务调度器" prop="jobId">
          <el-input v-model="form.jobId" placeholder="请输入任务调度器" />
        </el-form-item>
        <el-form-item label="任务调度器" prop="jobName">
          <el-input v-model="form.jobName" placeholder="请输入任务调度器" />
        </el-form-item>
        <el-form-item label="任务配置" prop="taskConf">
          <el-input
            v-model="form.taskConf"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="执行策略" prop="strategy">
          <el-input v-model="form.strategy" placeholder="请输入执行策略" />
        </el-form-item>
        <el-form-item label="描述" prop="dsc">
          <el-input v-model="form.dsc" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="校验结果"
      :visible.sync="resultOpen"
      width="800px"
      append-to-body
    >
      <p style="margin-top: 0">源表数量：{{ checkResult.sourceTableCount }}</p>
      <p>目标表数量：{{ checkResult.sinkTableCount }}</p>
      <el-table :data="checkResult.tables" style="width: 100%">
        <el-table-column prop="sourceTableName" label="源表名称" width="180">
        </el-table-column>
        <el-table-column prop="sinkTableName" label="目标表名称" width="180">
        </el-table-column>
        <el-table-column prop="sourceRowCount" align="center" label="源表行数">
        </el-table-column>
        <el-table-column prop="sinkRowCount" align="center" label="目标表行数">
        </el-table-column>
        <el-table-column
          prop="sourceColumnCount"
          align="center"
          label="源表列数"
        >
        </el-table-column>
        <el-table-column
          prop="sinkColumnCount"
          align="center"
          label="目标表列数"
        >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resultOpen = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="评估日志"
      :before-close="handleClose"
      :visible.sync="isLog"
      width="45%"
      destroy-on-close
    >
      <div class="textBox" ref="logBox" v-show="logFofText.length > 0">
        <p
          v-for="(item, index) in logFofText"
          :style="{ color: item.logLevel == 'error' ? 'red' : false }"
          :key="index"
        >
          {{ item.text }}
        </p>
      </div>
      <el-empty
        description="暂无日志"
        v-show="logFofText.length < 1"
      ></el-empty>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEnter">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTaskCheck,
  getTaskCheck,
  delTaskCheck,
  addTaskCheck,
  updateTaskCheck,
  delTaskCheckExecute,
  delTaskCheckScheduler,
} from "@/api/console/taskCheck";

import { dataTaskLogGetNew, dataTaskLogGetNewLog } from "@/api/console/tasks";

export default {
  name: "TaskCheck",
  dicts: ["taskstatus", "appraise_taskmode", "check_tasktype", "all_tasktype"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 校验任务表格数据
      taskCheckList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pgNum: 1,
        pgSize: 10,
        taskName: null,
        taskMode: null,
        taskType: null,
        sourceName: null,
        sinkName: null,
        taskStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      isLog: false,
      logFofText: [],
      timer: null,
      checkResult: {
        sourceTableCount: 3,
        sinkTableCount: 3,
        tables: [
          {
            sourceTableName: "class_info",
            sinkTableName: "class_info",
            sourceRowCount: "3",
            sinkRowCount: "0",
            sourceColumnCount: 4,
            sinkColumnCount: 0,
            isMatch: false,
          },
          {
            sourceTableName: "student",
            sinkTableName: "student",
            sourceRowCount: "5",
            sinkRowCount: "0",
            sourceColumnCount: 3,
            sinkColumnCount: 0,
            isMatch: false,
          },
          {
            sourceTableName: "teacher",
            sinkTableName: "teacher",
            sourceRowCount: "0",
            sinkRowCount: "0",
            sourceColumnCount: 4,
            sinkColumnCount: 0,
            isMatch: false,
          },
        ],
      },
      resultOpen: false,
      checkListTimer: null,
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getList();
      vm.checkListTimer = setInterval(() => {
        vm.getList();
      }, 3000);
    });
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(this.checkListTimer);
    this.checkListTimer = null;
    next();
  },
  methods: {
    getIndex($index) {
      return (
        (this.queryParams.pgNum - 1) * this.queryParams.pgSize + $index + 1
      );
    },
    handleResult(row) {
      this.$router.push({
        path: "/reports/index",
        query: { id: row.id, jobType: row.jobType, type: "check" },
      });
      // this.resultOpen = true;
    },
    /** 查询校验任务列表 */
    getList() {
      this.loading = false;
      listTaskCheck(this.queryParams).then((response) => {
        this.taskCheckList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskMode: null,
        taskType: null,
        sourceId: null,
        sourceName: null,
        sinkId: null,
        sinkName: null,
        jobId: null,
        jobName: null,
        taskConf: null,
        taskStatus: null,
        strategy: null,
        dsc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    handleEnter() {
      clearInterval(this.timer);
      this.timer = null;
      this.isLog = false;
      return;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pgNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // this.open = true;

      this.$router.push({ path: "/taskMain/taskMainAdd" });
      this.title = "添加校验任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.$router.push({
        path: "/taskMain/taskMainAdd",
        query: { id: row.id },
      });
      this.title = "更改校验任务";
      // const id = row.id || this.ids;
      // getTaskCheck(id).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改校验任务";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateTaskCheck(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTaskCheck(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除校验任务编号为"' + ids + '"的数据项？')
        .then(function () {
          return delTaskCheck({ idArray: Array.isArray(ids) ? ids : [ids] });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "console/taskCheck/export",
        {
          ...this.queryParams,
        },
        `taskCheck_${new Date().getTime()}.xlsx`
      );
    },
    handleExecute(row) {
      let that = this;
      let ids = row.id || this.ids;
      this.$modal.confirm("是否确认立即执行？").then(function () {
        const loading = that.$loading({
          lock: true,
          text: "执行中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        delTaskCheckExecute({
          id: ids,
        })
          .then((res) => {
            loading.close();
            that.$message.success("任务提交成功");
          })
          .catch((err) => {
            loading.close();
            that.$message.error("执行失败");
          });
      });
    },
    handleScheduler(row) {
      let that = this;
      let ids = row.id || this.ids;
      this.$modal.confirm("是否确认启动调度器？").then(function () {
        delTaskCheckScheduler({
          id: ids,
        })
          .then((res) => {
            that.$message.success("调度器启动成功");
          })
          .catch((err) => {
            that.$message.error("调度器启动失败");
          });
      });
    },
    async handleResultLog(row) {
      this.isLog = true;
      this.logFofText = [];
      let that = this;
      let res = await dataTaskLogGetNew({
        jobType: row.jobType,
        taskId: row.id,
      });
      let logText = JSON.parse(res.data.taskLog);
      logText.forEach((f) => {
        this.logFofText.push({
          text: `${f.time}：${f.logMsg}`,
          logLevel: f.logLevel,
        });
      });
      this.$nextTick(() => {
        let scrollElem = that.$refs.logBox;
        scrollElem.scrollTo({
          top: scrollElem.scrollHeight,
          behavior: "smooth",
        });
      });
      if (res.data.taskStatus == 0 || res.data.jobType == "SYNC_DATA") {
        that.timer = setInterval(async () => {
          res = await dataTaskLogGetNewLog({
            id: res.data.id,
          });
          if (res.data.taskStatus != 0) {
            clearInterval(that.timer);
            that.timer = null;
            let res = await dataTaskLogGetNew({
              jobType: row.jobType,
              taskId: row.id,
            });
            let logText = JSON.parse(res.data.taskLog);
            logText.forEach((f, i) => {
              if (f.logMsg.includes(logText[i])) return;
              this.logFofText.push({
                text: `${f.time}：${f.logMsg}`,
                logLevel: f.logLevel,
              });
            });
            this.$nextTick(() => {
              let scrollElem = that.$refs.logBox;
              scrollElem.scrollTo({
                top: scrollElem.scrollHeight,
                behavior: "smooth",
              });
            });
            return;
          }
          JSON.parse(res.data.taskLog).forEach((f) => {
            this.logFofText.push({
              text: `${f.time}：${f.logMsg}`,
              logLevel: f.logLevel,
            });
          });
          this.$nextTick(() => {
            let scrollElem = that.$refs.logBox;
            scrollElem.scrollTo({
              top: scrollElem.scrollHeight,
              behavior: "smooth",
            });
          });
        }, 1000);
      } else {
        clearInterval(this.timer);
        this.timer = null;
        return;
      }
    },
    handleClose() {
      this.isLog = false;
      clearInterval(this.timer);
      this.timer = null;
      this.logFofText = [];
      
    },
    async handleNewResult(row) {
      if (row.taskStatus != 2) {
        return this.$message.warning("任务未成功");
      }
      let res = await dataTaskLogGetNew({
        jobType: row.jobType,
        taskId: row.id,
      });
      window.open(`/report/verificationReport?id=${res.data.id}`);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__label {
  width: 100px !important;
}
.textBox {
  height: 300px;
  overflow-y: auto;
}
</style>
